#ifndef JFUTRUESYNCHRONIZER_H
#define JFUTRUESYNCHRONIZER_H

#include "jconcurrent_global.h"
#include "jfuture.h"

template <typename T>
class JFutureSynchronizer
{
public:
    JFutureSynchronizer() : m_cancelOnWait(false) { }
    explicit JFutureSynchronizer(const JFuture<T> &future)
        : m_cancelOnWait(false)
    { addFuture(future); }
    ~JFutureSynchronizer()  { waitForFinished(); }

    void setFuture(const JFuture<T> &future)
    {
        waitForFinished();
        m_futures.clear();
        addFuture(future);
    }

    void addFuture(const JFuture<T> &future)
    {
        m_futures.push_back(future);
    }

    void waitForFinished()
    {
        if (m_cancelOnWait) {
            for (size_t i = 0; i < m_futures.size(); ++i) {
                 m_futures[i].cancel();
            }
        }
        
        for (size_t i = 0; i < m_futures.size(); ++i) {
             m_futures[i].waitForFinished();
         }
    }

    void clearFutures()
    {
        m_futures.clear();
    }

    jlist<JFuture<T> > futures() const
    {
        return m_futures;
    }

    void setCancelOnWait(bool enabled)
    {
        m_cancelOnWait = enabled;
    }

    bool cancelOnWait() const
    {
        return m_cancelOnWait;
    }

protected:
    J_DISABLE_COPY(JFutureSynchronizer)
    jlist<JFuture<T> > m_futures;
    bool m_cancelOnWait;
};

#endif // JFUTRUESYNCHRONIZER_H
